package morning.cat.code;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;

import static feign.Util.ensureClosed;

/**
 * @describe: 类描述信息
 * @author: morningcat.zhang
 * @date: 2019/6/4 2:26 PM
 */
public class PersonDecoder implements Decoder {
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (response.status() == 404)
            return Util.emptyValueOf(type);
        if (response.body() == null)
            return null;
        Reader reader = response.body().asReader();
        try {
            return new Gson().fromJson(reader, type);
        } catch (JsonIOException e) {
            if (e.getCause() != null && e.getCause() instanceof IOException) {
                throw IOException.class.cast(e.getCause());
            }
            throw e;
        } finally {
            ensureClosed(reader);
        }
    }
}
